import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  // history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import('../views/detail/index.vue')
    },
    {
      path: '/auth',
      name: 'auth',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/auth/index.vue')
    },
    {
      path: '/code',
      name: 'code',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/code/index.vue')
    },
    {
      path: '/bind',
      name: 'bind',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/bind/index.vue')
    },
    {
      path: '/error/403',
      name: '403',
      component: () => import('../views/error/403.vue')
    },
    {
      path: '/record',
      name: 'record',
      component: () => import('../views/record/index.vue')
    }
  ]
})
const whiteList = ['/bind', '/error/403', '/auth', '/code']

router.beforeEach(async (to, from, next) => {
  console.log(to.path)
  var user = useUserStore()
  if (whiteList.includes(to.path)) {
    next()
  } else if (user.getToken()) {
    if (!user.phone || !user.shop) {
      next({ path: '/auth' })
    } else {
      next()
    }
  } else if (window.location.href.indexOf('code=') > -1) {
    let code = findCode()
    let orgin = window.location.href.split('?')[0]
    window.location.replace(orgin + '#/code?code=' + code)
    next({ path: '/code', query: { code: code } })
  } else {
    next({ path: '/error/403', query: { des: '打开方式错误 ', href: document.location.href } })
  }
})

function findCode() {
  try {
    return document.location.href.split('=')[1].replaceAll('&state', '')
  } catch (error) {
    return null
  }
}

export default router
